﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;

public partial class Admin_LearnObjs : System.Web.UI.Page
{
    ILE_Global ileGlobal = new ILE_Global();
    LearnObjsBLL learnObjLogic = new LearnObjsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            FillAllStandardsList();
            GridViewLearnObjs.Sort("Title", SortDirection.Ascending);
        }
    }

    protected void FillAllStandardsList()
    {
        StandardsBLL standardsLogic = new StandardsBLL();

        Standards.StandardsDataTable standards = standardsLogic.GetStandards();

        ddlistStandards.Items.Clear();

        foreach (Standards.StandardsRow standard in standards)
        {
            ListItem listItem = new ListItem(standard.Standard.ToString(), standard.StandardID.ToString());
            ddlistStandards.Items.Add(listItem);
            lstboxStandards.Items.Add(listItem);
            lstboxEditStandards.Items.Add(listItem);
        }
    }

    protected void ddlistStandards_SelectedIndexChanged(object sender, EventArgs e)
    {
        PanelLearnObjDetail.Visible = false;
        GridViewLearnObjs.SelectedIndex = -1;
    }

    protected void btnOpenCreateLearnObj_Click(object sender, EventArgs e)
    {
        MultiViewLearnObj.ActiveViewIndex = 1;
        lblUploadedFile.Text = "";
    }

    protected void btnCreateLearnObj_Click(object sender, EventArgs e)
    {
        string Title = txtLearnObjTitle.Text;
        string Link = txtLearnObjLink.Text;
        string EstimatedTime = txtEstimatedTime.Text;
        string Directions = txtDirections.Value;

        int LearnObjID = learnObjLogic.InsertLearnObj(Title, Link, Directions, EstimatedTime, String.Empty);
        if (LearnObjID != 0)
        {
            foreach (ListItem standard in lstboxStandards.Items)
            {
                if (standard.Selected)
                {
                    learnObjLogic.InsertRelation(LearnObjID, Convert.ToInt32(standard.Value));
                }
            }

            XDocument xDocQuiz = new XDocument();
            xDocQuiz.Declaration = new XDeclaration("1.0", "utf-8", "yes");

            xDocQuiz.Document.Add(new XElement("quiz",
                                    new XAttribute("name", "Quiz for " + Title),
                                    new XAttribute("learnobjid", LearnObjID.ToString()),
                                    new XAttribute("createdby", Session["UserID"].ToString()),
                                        new XElement("questions")));

            xDocQuiz.Element("quiz").Element("questions").Add(
                    new XElement("question", new XAttribute("id", "1"), new XAttribute("difficulty", "normal"), new XAttribute("point", "2"), new XAttribute("defaultrequired", "false"),
                        new XElement("questiontext", "New Quiz Question"),
                        new XElement("choices",
                            new XElement("choice", new XAttribute("iscorrectanswer", "true"), "Choice 1 Answer"),
                            new XElement("choice", new XAttribute("iscorrectanswer", "false"), "Choice 2"),
                            new XElement("choice", new XAttribute("iscorrectanswer", "false"), "Choice 3"),
                            new XElement("choice", new XAttribute("iscorrectanswer", "false"), "Choice 4"),
                            new XElement("choice", new XAttribute("iscorrectanswer", "false"), "Choice 5"))));

            learnObjLogic.UpdateLearnObj(Title, Link, EstimatedTime, Directions, xDocQuiz.ToString(), LearnObjID);

            // *SteveMsg
            string modalPopupMsg = "Learning Object has been created successfully.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 1);
            txtLearnObjTitle.Text = String.Empty;
            txtLearnObjLink.Text = "http://";
            lstboxStandards.SelectedIndex = -1;
            txtEstimatedTime.Text = String.Empty;
            txtDirections.Value = String.Empty;

            GridViewLearnObjs.DataBind();
        }
        else
        {
            // *SteveMsg
            string modalPopupMsg = "Failed to create the learning object.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
        }
    }

    protected void btnEditLearnObj_Click(object sender, EventArgs e)
    {
        string Title = txtEditLearnObjTitle.Text;
        string Link = txtEditLearnObjLink.Text;
        string EstimatedTime = txtEditEstimatedTime.Text;
        string Directions = txtEditDirections.Value;

        lblUploadedFile.Text = "";

        int LearnObjID = Convert.ToInt32(GridViewLearnObjs.SelectedDataKey.Value);

        try
        {
            learnObjLogic.UpdateLearnObj(Title, Link, EstimatedTime, Directions, learnObjLogic.GetLearnObj(LearnObjID).LearnObjQuizQuestions, LearnObjID);
            learnObjLogic.DeleteRelationByLearnObjID(LearnObjID);
            foreach (ListItem standard in lstboxEditStandards.Items)
            {
                if (standard.Selected)
                {
                    learnObjLogic.InsertRelation(LearnObjID, Convert.ToInt32(standard.Value));
                }
            }

            string modalPopupMsg = "Your Learning Object has been updated successfully.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 1);
            GridViewLearnObjs.DataBind();
            GridViewLearnObjs.SelectedIndex = -1;
            PanelLearnObjDetail.Visible = false;
        }
        catch (Exception ex)
        {
            string modalPopupMsg = "Failed to update the learnObj.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
            ileGlobal.RecordError("LearnObjs.aspx.cs:btnEditLearnObj_Click:000", ex, 5, Request.Browser);
        }
    }

    protected void btnOpenEditLearnObj_Click(object sender, EventArgs e)
    {
        MultiViewLearnObj.ActiveViewIndex = 0;
    }

    protected void GridViewLearnObjs_DataBound(object sender, EventArgs e)
    {
        if (GridViewLearnObjs.Rows.Count == 0)
        {
            PanelEmptyLearnObjMessage.Visible = true;
            PanelLearnObjDetail.Visible = false;
        }
        else
        {
            PanelEmptyLearnObjMessage.Visible = false;
        }
    }
    protected void GridViewLearnObjs_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GridViewLearnObjs.SelectedIndex >= 0)
        {
            int LearnObjID = Convert.ToInt32( GridViewLearnObjs.SelectedDataKey.Value );
            LearnObjs.LearnObjsRow learnObj = learnObjLogic.GetLearnObj(LearnObjID);
            txtEditLearnObjTitle.Text = learnObj.Title;
            if (learnObj.Link == "INTERNAL")
            {
                chkboxEditLearnObjIsInternal.Checked = true;
                txtEditLearnObjLink.Enabled = false;
                revEditLearnObjLink.Enabled = false;
            }
            else
            {
                chkboxEditLearnObjIsInternal.Checked = false;
                txtEditLearnObjLink.Enabled = true;
                revEditLearnObjLink.Enabled = true;
            }
            txtEditLearnObjLink.Text = learnObj.Link;
            txtEditEstimatedTime.Text = learnObj.EstimatedTime;
            txtEditDirections.Value = learnObj.Instruction;
            

            LearnObjs.RelationsLearnObjStandardDataTable relations = learnObjLogic.GetLearnObjStandardRelationshipsByLearnObjID(LearnObjID);

            if (relations.Count == 0)
            {
                lstboxEditStandards.SelectedIndex = -1;
            }
            else
            {
                foreach (ListItem standard in lstboxEditStandards.Items)
                {
                    standard.Selected = false;
                    foreach (LearnObjs.RelationsLearnObjStandardRow relation in relations)
                    {
                        if (standard.Value.ToString() == relation.StandardID.ToString())
                        {
                            standard.Selected = true;
                            break;
                        }
                    }
                }
            }
            
            PanelLearnObjDetail.Visible = true;
        }
        else
        {
            PanelLearnObjDetail.Visible = false;
        }
    }


    protected void btnManageLearnObjQuestions_Click(object sender, EventArgs e)
    {
        int LearnObjID = Convert.ToInt32( GridViewLearnObjs.SelectedDataKey.Value );
        Response.Redirect("Quiz.aspx?LearnObjID=" + LearnObjID.ToString());
    }


    protected void btnDeleteLearnObj_Click(object sender, EventArgs e)
    {
        int LearnObjID = Convert.ToInt32(GridViewLearnObjs.SelectedDataKey.Value);

        bool result = learnObjLogic.DeleteLearnObj(LearnObjID);

        if (result)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "The Learning Object has been successfully deleted.", 1, "LearnObjs.aspx");
        }
        else
        {
            ModalPopupMessage.ShowModalPopup("ILE Message", "Failed to delete the learning object", 2);
        }
    }

    protected void chkboxLearnObjIsInternal_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkbox = (CheckBox)sender;
        if (chkbox.Checked)
        {
            txtLearnObjLink.Text = "INTERNAL";
            revLearnObjLink.Enabled = false;
            txtLearnObjLink.Enabled = false;
        }
        else
        {
            txtLearnObjLink.Text = "http://";
            revLearnObjLink.Enabled = true;
            txtLearnObjLink.Enabled = true;
        }
    }

    protected void chkboxEditLearnObjIsInternal_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkbox = (CheckBox)sender;
        if (chkbox.Checked)
        {
            txtEditLearnObjLink.Text = "INTERNAL";
            
            revEditLearnObjLink.Enabled = false;
            txtEditLearnObjLink.Enabled = false;
        }
        else
        {
            int LearnObjID = Convert.ToInt32(GridViewLearnObjs.SelectedDataKey.Value);

            if (learnObjLogic.GetLearnObj(LearnObjID).Link.ToString() == "INTERNAL")
                txtEditLearnObjLink.Text = "http://";
            else
                txtEditLearnObjLink.Text = learnObjLogic.GetLearnObj(LearnObjID).Link.ToString();
            revEditLearnObjLink.Enabled = true;
            txtEditLearnObjLink.Enabled = true;
        }
    }
    protected void btnUploadFile_Click(object sender, EventArgs e)
    {
        if (FileUploadLearnObj.HasFile)
        {
            string fileExt = System.IO.Path.GetExtension(FileUploadLearnObj.FileName).ToLower();
            if (fileExt == ".aspx" || fileExt == ".cs" || fileExt == ".config" || fileExt == ".xsd" || fileExt == ".js" || fileExt == ".vb" || fileExt == ".asax" || fileExt == ".dll" || fileExt == ".exe")
            {
                lblUploadedFile.ForeColor = System.Drawing.Color.Red;
                lblUploadedFile.Text = "The file extention is not allowed to be uploaded.";
                return;
            }
            string filename = System.DateTime.Now.ToFileTimeUtc().ToString() + fileExt;
            FileUploadLearnObj.PostedFile.SaveAs(Server.MapPath("../Uploads") + "/" + filename);
            lblUploadedFile.ForeColor = System.Drawing.Color.Black;
            lblUploadedFile.Text = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath.ToString();
            lblUploadedFile.Text += "/Uploads/" + filename;
            lblUploadedFile.ToolTip = "Copy this URL and use it as an Image Link when inserting images. For multiple images, simply repeat the process.";
        }
    }
    protected void btnEditUploadFile_Click(object sender, EventArgs e)
    {
    //    if (FileEditUploadLearnObj.HasFile)
    //    {
    //        string fileExt = System.IO.Path.GetExtension(FileEditUploadLearnObj.FileName).ToLower();
    //        if (fileExt == ".aspx" || fileExt == ".cs" || fileExt == ".config" || fileExt == ".xsd" || fileExt == ".js" || fileExt == ".vb" || fileExt == ".asax" || fileExt == ".dll" || fileExt == ".exe")
    //        {
    //            lblEditUploadedFile.ForeColor = System.Drawing.Color.Red;
    //            lblEditUploadedFile.Text = "The file extention is not allowed to be uploaded.";
    //            return;
    //        }
    //        string filename = System.DateTime.Now.ToFileTimeUtc().ToString() + fileExt;
    //        FileEditUploadLearnObj.PostedFile.SaveAs(Server.MapPath("../Uploads") + "/" + filename);
    //        lblEditUploadedFile.ForeColor = System.Drawing.Color.Black;
    //        lblEditUploadedFile.Text = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath.ToString();
    //        lblEditUploadedFile.Text += "/Uploads/" + filename;
    //        lblEditUploadedFile.ToolTip = "Copy this URL and use it as an Image Link when inserting images. For multiple images, simply repeat the process.";
    //    }
    }
}